﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;


namespace IdentificationCardCheck
{
    public partial class Form1 : Form
    {
        public string IdCardNum;
        public Form1()
        {
            InitializeComponent();
        }

        private void EnterTextBox_TextChanged(object sender, EventArgs e)
        {
            IdCardNum = EnterTextBox.Text;
        }

        private void CheckLegal_Click(object sender, EventArgs e)
        {
            string pattern1 = "^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$";//1900年到2099年，非闰年出生身份证号格式

            string pattern2 = "^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|(1|2)[0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|(1|2)[0-9]))[0-9]{3}[0-9Xx]$";//1900年到2099年，闰年出生身份证号格式

            int[] id = new int[20];
            for(int m = 0; m < 18; m++)
            {
                id[m] = int.Parse(IdCardNum[m].ToString());
            }

            int[] checkweight = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };

            int checkResult = 0;
            for(int i = 0; i < 17; i++)
            {
                checkResult = checkResult + id[i] * checkweight[i];
            }
            checkResult = checkResult % 11;
            string[] lastChar = {"1","0","X","9","8","7","6","5","4","3","2"};


            if ((Regex.IsMatch(IdCardNum, pattern1)) | (Regex.IsMatch(IdCardNum, pattern2)))
            {
                FormLegal.Text = "格式合法性：身份证格式合法！";
            }
            else
            {
                FormLegal.Text = "格式合法性：身份证格式不合法！请重新输入";
            }
            if(lastChar[checkResult] == IdCardNum[17].ToString())
            {
                LastLegal.Text = "最后一位有效性：校验通过，有效！";
            }
            else
            {
                LastLegal.Text = "最后一位有效性：校验不通过，请重新输入！";
            }

        }
    }
}
